package com.sunspring.zdcall.controller.commoncontroller;

import com.sunspring.zdcall.common.SimpleResponse;
import com.sunspring.zdcall.common.constant.WebConstant;
import com.sunspring.zdcall.common.exception.ZdException;
import com.sunspring.zdcall.entity.ZdLoginLog;
import com.sunspring.zdcall.service.LoginLogService;
import com.sunspring.zdcall.service.UserService;
import com.sunspring.zdcall.support.ContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

/**
 * @Author WuLei
 * @Date 2018/12/3  11:52
 */
@Controller
@Slf4j
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private LoginLogService loginLogService;


    @GetMapping("/login")
    public String loginPage() {
        return "redirect:/backstage/adminlogin.html";
    }

//    @PostMapping("/sys/adminLogin")
//    @ResponseBody
//    public SimpleResponse adminLogin(String username,String password,HttpServletRequest request) {
//        if (StringUtils.isBlank(username)) {
//            throw new ZdException("用户名不能为空");
//        }
//        if (StringUtils.isBlank(password)) {
//            throw new ZdException("密码不能为空");
//        }
//        User userInfo = userService.userLogin(username,password);
//        HttpSession session = request.getSession();
//        session.setAttribute(WebConstant.SESSION_LOGIN_KEY,userInfo);
//        //异步记录登录日志
//        String ip = request.getRemoteAddr();
//        ZdLoginLog loginLog = ZdLoginLog.login(new Date(),userInfo.getUserId(),ip);
//        loginLogService.add(loginLog);
//        return SimpleResponse.success(userInfo);
//    }

    @PostMapping("/sys/logout")
    public void userLogout(HttpServletRequest request,HttpServletResponse response) {
        try {
            request.getSession().removeAttribute(WebConstant.SESSION_LOGIN_KEY);
            response.sendRedirect("/login");
        } catch (IOException e) {
            log.error("退出失败" + e.getMessage());
        }

    }

    @GetMapping("/currentUser")
    @ResponseBody
    public SimpleResponse currentUser(HttpServletRequest request) {
        return SimpleResponse.success(ContextHolder.get());
    }

}
